import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';

//我的图片界面
class MyImage extends StatefulWidget {
  String token;
  MyImage(this.token);
  @override
  _MyImage createState() => new _MyImage();
}

class _MyImage extends State<MyImage> {

  File _image;
  String _imageLink;
  List urls;
  Response response;
  int code;

  void initState(){
    super.initState();
    _getAllImage();
  }

  //获取所有图片
  _getAllImage(){
    Dio().post("http://121.196.101.7:8080/treehole/diary/allImage",
        options:Options(headers: {"Token":widget.token},) ).then((value) {
      response=value;
      print(response.data);
      code=response.data["code"];
      if(code==0){
        setState(() {
          this.urls=response.data["data"];
        });
      }else{
        Fluttertoast.showToast(
          msg: "获取失败，请重试",
          backgroundColor: Colors.amber[50],
          textColor: Colors.black,
          fontSize: 15,
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,);
      }
    });
  }

//选择图片
  Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);//从图库选择图片
    // var image = await ImagePicker.pickImage(source: ImageSource.camera);使用相机
    _upLoadImage(image);//上传图片
    setState(() {
      _image = image;
    });
  }

  //上传图片
  _upLoadImage(File image) async {
    String path = image.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
        FormData formdata = FormData.fromMap({
          "image": await MultipartFile.fromFile(path, filename:name)
        });

    var response = await Dio().post("http://121.196.101.7:8080/treehole/diary/addImage", options:Options(headers: {
      "Token":widget.token}),queryParameters: {"url":path});
    print(response.data);
    if (response.data["code"] == 0) {
      Fluttertoast.showToast(
        msg: "图片上传成功",
        backgroundColor: Colors.greenAccent[100],
        textColor: Colors.black,
        fontSize: 15,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
      );
      _getAllImage();


    }else{
      Fluttertoast.showToast(
        msg: "图片上传失败，请重试",
        backgroundColor: Colors.greenAccent[100],
        textColor: Colors.black,
        fontSize: 15,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
      );
    }
  }


  List<Widget> images(){
    var _images=urls.map((value){
      return Container(
        margin: EdgeInsets.all(7),
        child: Image.file(File(value["url"]),fit: BoxFit.cover,),
      );
    });
    return _images.toList();
  }



  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('我的图片',style:TextStyle(color: Colors.black)),
        backgroundColor: Colors.white70,
        leading: IconButton(
          icon:Icon(Icons.arrow_back,color: Colors.black),
          onPressed: () {Navigator.pop(context);},
        ),
      ),
      body:urls==null?
          Container(
            child: Text("还没有图片哦"),
          ):
      GridView.count(
          crossAxisCount: 3,
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
          childAspectRatio: 1,
          children: images(),
      ),


      backgroundColor: Colors.amber[50],
      floatingActionButton: FloatingActionButton(
        onPressed: getImage,
        tooltip: '选择图片',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }



}